// TestState:
// 0 = Init state;
// 1 = Sample Sended;
// 2 = Sample Received;
//------------------
// Два состояния = результы тестирования:
// 3 = Successfully;
// 4 = Failed(Wait timeout);

desc:CheckLatency(Sender) v1-3

slider1:CheckLatency=0<0,1,1{OFF,RUN TEST}>Measure Audio Latency:
slider2:treshold_db=-12<-60,0,1>Receive Treshold(dB):

slider4:TestState=0<0,4,1{Init,Send-OK,Receive-OK,DONE,WaitTimeout}>Test State / Result:
slider5:latency_spls=0<0,10000,1>Latency(samples):
slider6:latency_ms=0<0,1000,1>Latency(ms):

@init
ext_noinit = 1;
_global.TestState = 0;

@slider

@block
TestState = _global.TestState;

@sample
spl0 = spl1 = 0; // reset input samples

// Run Test
CheckLatency ? (
  CheckLatency = 0;
  latency_spls = 0;
  latency_ms   = 0;
  _global.waiting = 0; // reset count
  _global.wait_max = srate; // max waiting(in samples)
  _global.treshold = 10^(treshold_db/20);
  spl0 = spl1 = 1; // test sample
  _global.TestState = 1; // 1 = SampleSended
);

// If Test Sample is successfully received then update latency info
_global.TestState == 2 ? (  // 2 = SampleReceived
  latency_spls = _global.waiting;
  latency_ms   = (latency_spls/srate) * 1000;
  _global.TestState = 3;    // 3 = Successfully
);
